import {
    createRouter,
    createWebHashHistory
} from 'vue-router'

import Admin from "~/layouts/admin.vue";
import Index from '~/pages/index.vue'
import Login from '~/pages/login.vue'
import NotFound from '~/pages/404.vue'
import UserList from '~/pages/user/list.vue'
import UserDetail from '~/pages/user/detail.vue'
import RuleList from '~/pages/rule/list.vue'
import RuleDetail from '~/pages/rule/detail.vue'
import RoleList from '~/pages/role/list.vue'
import RoleDetail from '~/pages/role/detail.vue'
import AllotRole from '~/pages/role/allot-role.vue'



//非菜单路由
const routes = [
    {
        path: "/",
        name: "admin",
        component: Admin,
    },
    {
        path: "/login",
        component: Login,
        meta: {
            title: "登录页"
        }
    }, {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound
    }
]

//动态路由，用户匹配菜单动态添加路由
const asyncRoutes = [
    {
        path: "/",
        name:"/",
        component: Index,
        meta: {
            title: "后台首页",
        }
    }, {
        path: "/user/list",
        name:"/user/list",
        component: UserList,
        meta: {
            title: "账号管理",
        }
    },{
        path: "/user/detail",
        name:"/user/detail",
        component: UserDetail,
        meta: {
            title: "账号详情",
        }
    },{
        path: "/role/list",
        name:"/role/list",
        component: RoleList,
        meta: {
            title: "角色管理",
        }
    },{
        path: "/role/detail",
        name:"/role/detail",
        component: RoleDetail,
        meta: {
            title: "角色详情",
        }
    },{
        path: "/role/allot-role",
        name:"/role/allot-role",
        component: AllotRole,
        meta: {
            title: "角色权限分配",
        }
    },
    {
        path: "/rule/list",
        name:"/rule/list",
        component: RuleList,
        meta: {
            title: "功能管理",
        }
    },{
        path: "/rule/detail",
        name:"/rule/detail",
        component: RuleDetail,
        meta: {
            title: "功能详情",
        }
    }
]



export const router = createRouter({
    history: createWebHashHistory(),
    routes
})


//动态路由,递归添加
export function addRoutes(menus){
    //是否有新的路由
    let hasNewRoute = false
    const findAndAddRoutesByMenus = (arr) =>{
        arr.forEach(e => {
            let item = asyncRoutes.find(o=>o.path == e.route)
            if(item && !router.hasRoute(item.path)){
                router.addRoute("admin",item)
                hasNewRoute = true
            }
            if(e.children && e.children.length >0){
                findAndAddRoutesByMenus(e.children)
            }
        });
    }
    findAndAddRoutesByMenus(menus)
    return hasNewRoute
}

